package com.lagou.rpcprovider;

import com.lagou.service.IUserService;
import com.lagou.service.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
@Service
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    @Autowired
    IUserService userService;

    ApplicationContext applicationContext;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest)msg;
        String className = rpcRequest.getClassName();
        String methodName = rpcRequest.getMethodName();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Object[] parameters = rpcRequest.getParameters();
        Class<?> aClass = Class.forName(className);
        Object bean = applicationContext.getBean(aClass);

        Class<?> beanClass = bean.getClass();

        Method method = beanClass.getMethod(methodName, parameterTypes);

        Object invoke = method.invoke(bean, parameters);

        ctx.writeAndFlush(invoke);

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
